﻿#if UNITY_EDITOR

using System.Collections.Generic;
using System.Reflection;
using UnityEngine;

namespace AI.Graph.Editor {


    public static class PortReferenceManager {

        /// <summary>
        /// Returns a list of all port attributes of the given node.
        /// </summary>
        static List<PortField> GetPortFields (Node node) {
            List<PortField> declarations = new List<PortField> ();

            foreach (FieldInfo portField in node.GetFields<ConnectionPort> ()) {
                Port portAttribute = portField.GetAttribute<Port> (true);

                if (portAttribute != null) {
                    declarations.Add (new PortField (portField, portAttribute));
                }
                else {
                    Debug.LogWarning ("The field [" + portField.Name + "] has no Port Attribute field.");
                }
            }

            return declarations;
        }


        /// <summary>
        /// Creates all ConnectionPorts for the given Node.
        /// </summary>
        /// <param name="node">Creates ConnectionPorts for this node.</param>
        internal static void CreateConnectionPorts (Node node) {
            foreach (PortField portField in GetPortFields (node)) {
                ConnectionPort port = portField.fieldInfo.GetValue (node) as ConnectionPort;

                // Create new port from field.
                port = portField.portAttribute.CreateNew (node);
                portField.fieldInfo.SetValue (node, port);
            }
        }


        struct PortField {

            public FieldInfo fieldInfo;
            public Port portAttribute;


            public PortField (FieldInfo fieldInfo, Port portAttribute) {
                this.fieldInfo = fieldInfo;
                this.portAttribute = portAttribute;
            }

        }

    }


}
#endif